package main

import (
	"fmt"
	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris/v12"
	"knife4g-server/conf"
	"knife4g-server/route"
	"os"
)

func main() {
	s := `
----------------------------------------------------------------------------
    __ __       _ ____     __ __           _____                          
   / //_/____  (_) __/__  / // / ____ _   / ___/___  ______   _____  _____
  / ,<  / __ \/ / /_/ _ \/ // /_/ __ ` + "`" + `/   \__ \/ _ \/ ___/ | / / _ \/ ___/
 / /| |/ / / / / __/  __/__  __/ /_/ /   ___/ /  __/ /   | |/ /  __/ /
/_/ |_/_/ /_/_/_/  \___/  /_/  \__, /   /____/\___/_/    |___/\___/_/
                              /____/
---------------------------------------------------------------------------
CopyRight©2025 sin3degrees All Rights Reserved
Knife4g Server Version: 0.3.1
---------------------------------------------------------------------------
`
	fmt.Print(s)
	app := newApp()
	route.InitRouter(app)
	var runner iris.Runner
	if conf.Config.Tls.Enable {
		if conf.Config.Tls.Auto {
			runner = iris.AutoTLS(conf.Config.Port, conf.Config.Tls.Domain, conf.Config.Tls.Email)
		} else {
			certFile := conf.Config.Tls.CertFile
			keyFile := conf.Config.Tls.KeyFile
			if certFile == "" || keyFile == "" {
				panic("tls certFile or keyFile is empty")
			}
			cert, err := os.ReadFile(certFile)
			if err != nil {
				panic(err)
			}
			key, err := os.ReadFile(keyFile)
			if err != nil {
				panic(err)
			}
			runner = iris.TLS(conf.Config.Port, string(cert), string(key))
		}
	} else {
		runner = iris.Addr(":" + conf.Config.Port)
	}
	err := app.Run(runner, iris.WithoutServerError(iris.ErrServerClosed))
	if err != nil {
		panic(err)
	}
}

func newApp() *iris.Application {
	app := iris.New()
	app.Configure(iris.WithOptimizations)
	crs := cors.New(cors.Options{
		AllowedOrigins:   conf.Config.Cors.Origins, // allows everything, use that to change the hosts.
		AllowCredentials: conf.Config.Cors.Enable,
		AllowedHeaders:   conf.Config.Cors.Headers,
		AllowedMethods:   []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
	})
	app.Use(crs)
	app.AllowMethods(iris.MethodOptions)
	// 定义基本认证中间件
	basicAuthHandler := func(ctx iris.Context) {
		username, password, ok := ctx.Request().BasicAuth()
		// 验证用户名和密码
		if !ok || username != conf.Config.BasicAuth.Username || password != conf.Config.BasicAuth.Password {
			ctx.StatusCode(iris.StatusUnauthorized)
			ctx.Header("WWW-Authenticate", `Basic realm="Restricted"`)
			_ = ctx.JSON(iris.Map{"error": "Unauthorized"})
			return
		}
		// 认证通过，继续处理请求
		ctx.Next()
	}
	// 注册基本认证中间件
	if conf.Config.BasicAuth.Enable {
		app.Use(basicAuthHandler)
	}
	return app
}
